import request from '../../../utils/request'

Page({
  data: {
    // 表单数据
    name: "",          // 预约人姓名
    phone: "",         // 预约人手机号
    family: "",        // 家人姓名
    date: "",          // 预约日期
    period: "morning", // 当前时间段：morning/afternoon
    selectedTime: "",  // 选中的时间
    minDate: "",       // 最小可选日期（当天）
    
    // 时间列表（模拟后端返回，可动态请求）
    morningTimes: [
      { time: "08:00", disabled: false },
      { time: "08:30", disabled: false },
      { time: "09:00", disabled: false },
      { time: "09:30", disabled: false },
      { time: "10:00", disabled: false },
      { time: "10:30", disabled: false },
      { time: "11:00", disabled: false },
      { time: "11:30", disabled: false },
      { time: "12:00", disabled: false }
    ],
    afternoonTimes: [
      { time: "12:30", disabled: false },
      { time: "13:00", disabled: false },
      { time: "13:30", disabled: false },
      { time: "14:00", disabled: false },
      { time: "14:30", disabled: false },
      { time: "15:00", disabled: false },
      { time: "15:30", disabled: false },
      { time: "16:00", disabled: false },
      { time: "16:30", disabled: false },
      { time: "17:00", disabled: false },
      { time: "17:30", disabled: false }
    ],
    
    // 提示框状态
    showToast: false,
    toastMsg: "此手机号已预约该时间"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // 设置最小可选日期为当天
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    this.setData({
      minDate: `${year}-${month}-${day}`
    });
  },

  // 输入事件：预约人姓名
  onNameInput(e) {
    this.setData({ name: e.detail.value });
  },

  // 输入事件：预约人手机号
  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },

  // 输入事件：家人姓名
  onFamilyInput(e) {
    this.setData({ family: e.detail.value });
  },

  // 日期选择事件（转换为「YYYY.MM.DD」格式，并更新时间段可用性）
  onDateChange(e) {
    const formatDate = e.detail.value.replace(/-/g, '.');
    this.setData({ 
      date: formatDate,
      selectedTime: "" // 清空已选时间
    });
    
    // 检查是否是当天，如果是则禁用已过时间段
    this.updateTimeAvailability(e.detail.value);
  },

  /**
   * 根据选择的日期更新时间段可用性
   */
  updateTimeAvailability(selectedDate) {
    const today = new Date();
    const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
    
    // 如果选择的不是当天，所有时间都可用
    if (selectedDate !== todayStr) {
      const morningTimes = this.data.morningTimes.map(item => ({...item, disabled: false}));
      const afternoonTimes = this.data.afternoonTimes.map(item => ({...item, disabled: false}));
      this.setData({ morningTimes, afternoonTimes });
      return;
    }
    
    // 选择的是当天，需要禁用已过的时间
    const currentHour = today.getHours();
    const currentMinute = today.getMinutes();
    const currentTime = currentHour * 60 + currentMinute; // 转换为分钟数便于比较
    
    // 更新上午时间段
    const morningTimes = this.data.morningTimes.map(item => {
      const [hour, minute] = item.time.split(':').map(Number);
      const timeInMinutes = hour * 60 + minute;
      return {
        ...item,
        disabled: timeInMinutes <= currentTime
      };
    });
    
    // 更新下午时间段
    const afternoonTimes = this.data.afternoonTimes.map(item => {
      const [hour, minute] = item.time.split(':').map(Number);
      const timeInMinutes = hour * 60 + minute;
      return {
        ...item,
        disabled: timeInMinutes <= currentTime
      };
    });
    
    this.setData({ morningTimes, afternoonTimes });
  },

  // 上下午切换事件
  switchPeriod(e) {
    const period = e.currentTarget.dataset.period;
    this.setData({ period });
  },

  // 时间选择事件（跳过禁用时间）
  selectTime(e) {
    if (e.currentTarget.dataset.disabled) return; // 禁用状态不响应
    const time = e.currentTarget.dataset.time;
    this.setData({ selectedTime: time });
  },

  // 预约提交事件
  onSubmit() {
    // 1. 获取全局userId
  const app = getApp();
  const wxUserId = app.globalData.userId; // 全局用户ID

  // 2. 校验登录状态（如果未登录，阻止提交并提示）
  if (!wxUserId) {
    wx.showToast({ 
      title: "请先登录", 
      icon: "none" 
    });
    // 可选：3秒后跳转到登录页
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/my/myindex/myindex' // 登录页路径
      });
    }, 1500);
    return;
  }
    // 1. 基础表单校验
    const { name, phone, family, date, selectedTime } = this.data;
    if (!name) {
      wx.showToast({ title: "请填写预约人姓名", icon: "none" });
      return;
    }
    if (!phone || !/^1\d{10}$/.test(phone)) {
      wx.showToast({ title: "请填写正确的手机号", icon: "none" });
      return;
    }
    if (!family) {
      wx.showToast({ title: "请填写家人姓名", icon: "none" });
      return;
    }
    if (!date) {
      wx.showToast({ title: "请选择预约日期", icon: "none" });
      return;
    }
    if (!selectedTime) {
      wx.showToast({ title: "请选择预约时间", icon: "none" });
      return;
    }

    // 2. 调用后端接口提交预约
    const appointmentData = {
      wxUserId: wxUserId, // 加入全局用户ID
      appointmentType: "1", // 探访预约
      applicantName: name,
      phone: phone,
      appointmentTime: date.replace(/\./g, '-') + ' ' + selectedTime + ':00',
      status: "1" // 待确认（数字字符串，与数据库保持一致）
    };

    wx.showLoading({
      title: '提交中...'
    });

    request({
      url: '/le/registration/miniApp',
      method: 'POST',
      data: appointmentData,
      success: (res) => {
        wx.hideLoading();
        if (res.data && res.data.code === 200) {
          wx.showToast({ 
            title: "预约成功",
            icon: "success"
          });
          // 清空表单
          this.setData({
            name: "",
            phone: "",
            family: "",
            date: "",
            selectedTime: ""
          });
        } else {
          wx.showToast({ 
            title: res.data.msg || "预约失败", 
            icon: "none" 
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('预约提交失败:', err);
        wx.showToast({ 
          title: "网络错误，请重试", 
          icon: "none" 
        });
      }
    });
  }
});